<template>
	<view class="login_box">
		<view class="login-bg">
			<view class="header">
				<view class="back" @click="backdata">返回</view>
				登录
			</view>
			<view class="login-logo">
				<img src="../../static/img/logo-JZ.png" alt="">
			</view>
			<view class="sub">
				<button type="primary" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">手机号快捷登录</button>
			</view>

		</view>

	</view>
</template>

<script>
	import {
		PostcodeTsession,
		PostuserinfoDecrypt,
		PostbindStatus,
		PostbindUser,
		PostOauthToken,
		getBaseUserinfo
	} from '@/common/api/index.js'
	export default {
		components: {},
		data() {
			return {
				appId: 'wx4779deef6c5ffd2f',
				detailObj: {},
				codesessionInfo: {},
				decryptInfo: {}
			}
		},
		methods: {
			baseUserinfo(){
				getBaseUserinfo().then(res => {
					console.log(res)
					if (res.code == 200) {
						console.log('请求成功:', res.data);
							wx.setStorage({
								key: 'userinfo',
								data: res.data,
								success: function() {
									// console.log('存储成功');
								}
							});
							
							uni.showToast({
								title: '登录成功',
								icon: 'none',
								duration: 3000
							})
							setTimeout(()=>{
								uni.reLaunch({
									url: '/pages/index/index'
								})
							},1500)
							}
				})
			},
			createMultipartFormData(data) {
			  // 自定义分隔符
			  const boundary = '------WebKitFormBoundarygsrUJoxlD7gpAywg';
			  let formData = '';
			
			  // 遍历数据对象，构造每个表单字段
			  for (let key in data) {
			    formData += `--${boundary}\r\n`;
			    formData += `Content-Disposition: form-data; name="${key}"\r\n\r\n`;
			    formData += `${data[key]}\r\n`;
			  }
			
			  // 结束分隔符
			  formData += `--${boundary}--\r\n`;
			
			  return {
			    body: formData,  // 构造好的请求体
			    boundary: boundary
			  };
			},
			oauthToken(){
				const bodys =this.createMultipartFormData({
						"appid": this.appId,
						"openid": this.codesessionInfo.openid,
						"grant_type":'wx_mini' ,
						"phone_no": this.decryptInfo.purePhoneNumber
					})
					let thats=this
				wx.request({
				  url: 'https://test.imaibj.cn/oauth/token',  // 替换为实际的接口地址
				  method: 'POST',
				  header: {
				    'Content-Type': `multipart/form-data; boundary=${bodys.boundary}`,  // 设置请求头，指定 boundary
					'Authorization': `Basic RlBCaEw5a1lDSG5TSmJCMTdVRmcyajFIOmVMQ0JUdUEyQlp5aTM0eTBmT2JuVFdlb3ZpcFVUOUhuWEtvZUN5WkVSWmFRQXhVRQ==`, 
				  },
				  data: bodys.body,  // 传递构造好的请求体
				  success(res) {
					  let that=thats
				    console.log('请求成功:', res.data);
					if(res.statusCode==200){
						
						
						// console.log(that.decryptInfo)
						// wx.setStorage({
						// 	key: 'userinfo',
						// 	data: that.decryptInfo,
						// 	success: function() {
						// 		// console.log('存储成功');
						// 	}
						// });
						wx.setStorage({
							key: 'token',
							data: res.data,
							success: function() {
								// console.log('存储成功');
							}
						});
						
						// uni.showToast({
						// 	title: '登录成功',
						// 	icon: 'none',
						// 	duration: 3000
						// })
						that.baseUserinfo()
						// setTimeout(()=>{
						// 	uni.reLaunch({
						// 		url: '/pages/index/index'
						// 	})
						// },1500)
					}
					
				  },
				  fail(err) {
				    console.error('请求失败:', err);
				  }
				});
			},
			generateUniqueId() {
				return 'xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					const r = Math.random() * 16 | 0,
						v = c === 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},

			onGetPhoneNumber(e) {

				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户拒绝授权  
					return
				} else {
					this.detailObj = e.detail
					this.wxLogin()
				}
			},
			wxLogin() {
				uni.showToast({
					title: '登录中...',
					icon: 'none',
					duration: 40000
				})
				let that = this
				wx.login({
					success(res) {
						let thats = that;
						if (res.code) {
							console.log(res)
							PostcodeTsession({
								"js_code": res.code,
								"appid": thats.appId
							}).then(result => {
								if (result.status == '00000') {
									thats.codesessionInfo = result.data
									thats.decryptData(result.data)
								}
							})
						}
					}
				})
			},
			decryptData(objs) {
				let that = this;
				PostuserinfoDecrypt({
					"session_key": objs.session_key,
					"app_id": this.appId,
					"iv": this.detailObj.iv,
					"encrypted_data": this.detailObj.encryptedData
				}).then(result => {
					// console.log(result)
					if(result.status=='00000'){
					that.decryptInfo = result.data
					that.bindStatusData(result.data)
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			bindStatusData(e) {
				PostbindStatus({
					"client_id": this.codesessionInfo.client_id,
					"phone_no": e.purePhoneNumber
				}).then(result => {
					console.log(result)
					// this.decryptInfo=result.data
					if (!result.data) {
						this.bindUserData()
						// wx.setStorage('userInfo', this.decryptInfo); 
					} else {
						// console.log(this.decryptInfo)
						let that=this
						that.oauthToken()
						// wx.setStorage({
						// 	key: 'userinfo',
						// 	data: that.decryptInfo,
						// 	success: function() {
						// 		// console.log('存储成功');
						// 	}
						// });
						
						// uni.showToast({
						// 	title: '登录成功',
						// 	icon: 'none',
						// 	duration: 3000
						// })
						// setTimeout(()=>{
						// 	uni.reLaunch({
						// 		url: '/pages/index/index'
						// 	})
						// },1500)
					}
				})
			},
			bindUserData() {
				PostbindUser({
					"appid": this.appId,
					"phone_no": this.decryptInfo.purePhoneNumber,
					"openid": this.codesessionInfo.openid
				}).then(result => {
					console.log(result)
					let that=this
					// this.decryptInfo=result.data
					if (result.status == '00000') {
						// console.log(result)
						wx.setStorage({
							key: 'userinfo',
							data: {
								userInfo: that.decryptInfo
							},
							success: function() {
								// console.log('存储成功');
							}
						});
						uni.showToast({
							title: '登录成功',
							icon: 'none',
							duration: 3000
						})
						setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/index/index'
							})
						},1500)
						

					} else {
						wx.setStorage({
							key: 'userinfo',
							data: {
								userInfo: ''
							},
							success: function() {
								// console.log('存储成功');
							}
						});
						uni.showToast({
							// title: result.message,
							title: '请到京转网页进行注册再使用小程序',
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			backdata() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}


		},
		onLoad(option) {},
		mounted() {
			wx.setStorage({
				key: 'userinfo',
				data: '',
				success: function() {
					
				}
			});
		}
	}
</script>

<style scoped lang="less">
	.login_box {
		width: 100%;
		height: calc(100vh - 45px);
		background-color: #F1F6FA;
		color: #333333;
		padding-top: 80rpx;

		.login-bg {
			background-image: url(../../static/img/my-bg.png);
			background-repeat: no-repeat;
			background-size: 100% auto;
			height: 100%;
		}

		.login-logo {
			margin-top: 30%;
			text-align: center;

			img {
				width: 300rpx;
				height: 150rpx;
			}
		}

		.header {
			position: relative;
			padding: 15rpx 60rpx 0rpx;
			font-size: 36rpx;
			font-weight: 600;
			line-height: 60px;
			height: 60px;
			text-align: center;

			.back {
				position: absolute;
				left: 5%;
			}
		}

		.sub {
			margin-top: 10%;
			width: 100%;

			button {
				width: 70%;
				background-color: #1664FF;
			}
		}
	}
</style>